#include <STC15F2K60S2.H>
#include <intrins.h>

#include "tool.h"


#define LED 					          P0 									//led灯
#define DIGITAL_TUBE 	          P0									//数码管
#define DIGITAL_TUBE_IDEX 	    P0									//数码管
#define LATCH 				          P2									//锁存器

#define LAST_3_BITS_MASK_8      0xe0								//最后三位的掩码

typedef unsigned char u8;
typedef unsigned int u16;

typedef enum 
{
	Led=0x80,
	Digital_tube=0xe0,
	Digital_tube_idex=0xc0
}Latch_mode;

//共阳
u8 code table_sun[]={
	0xc0,  //0
	0xf9,  //1
	0xa4,  //2
	0xb0,  //3
	0x99,  //4
	0x92,  //5
	0x82,  //6
	0xf8,  //7
	0x80,  //8
	0x90,  //9
	0x88,  //A
	0x83,  //B
	0xc6,  //C
	0xa1,  //D
	0x86,  //E
	0x8e,  //F
	0x8c,  //P
	0xc1,  //U
	0x91,  //Y
	0x7c,  //L
	0x00,  //全亮
	0xff   //熄灭
};

//共阴
u8 code table_moon[]={
	0x3F,  //"0"
	0x06,  //"1"
	0x5B,  //"2"
	0x4F,  //"3"
	0x66,  //"4"
	0x6D,  //"5"
	0x7D,  //"6"
	0x07,  //"7"
	0x7F,  //"8"
	0x6F,  //"9"
	0x77,  //"A"
	0x7C,  //"B"
	0x39,  //"C"
	0x5E,  //"D"
	0x79,  //"E"
	0x71,  //"F"
	0x76,  //"H"
	0x38,  //"L"
	0x37,  //"n"
	0x3E,  //"u"
	0x73,  //"P"
	0x5C,  //"o"
	0x40,  //"-"
	0x00,  //熄灭
	0xff   //全亮
};
u8 idex[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};


void Delay1ms();
void init();
void display_digital_tube(u8 idex,u8 number,bool have_point);
void display_led(u8 led);
void display_number2(int idex,int number);

void main(){
	
	int Minutes=0;//分
	int seconds=0;//秒
	int milliseconds=0;//毫秒

	init();
	
	while(1){
		display_number2(0,Minutes);
		display_digital_tube(idex[2],0xbf,false);//显示横线
		display_number2(3,seconds);
		display_digital_tube(idex[5],0xbf,false);//显示横线
		display_number2(6,milliseconds/10);
		if(milliseconds>=1000){
			milliseconds=0;
			if(seconds>=60){
				seconds=0;
				Minutes=(Minutes+1)%60;
			}else{
				seconds++;
			}
		}else{
			milliseconds++;
		}
	}
	
}

void Delay1ms()		//@11.0592MHz
{
	unsigned char i, j;

	_nop_();
	_nop_();
	_nop_();
	i = 11;
	j = 190;
	do
	{
		while (--j);
	} while (--i);
}

void init(){
	P0=0x00;
}

void display_led(u8 led){
	LATCH=(LATCH&~LAST_3_BITS_MASK_8)|Led;
	
	LED=led;
	
	LATCH=LATCH&~LAST_3_BITS_MASK_8;//关闭锁存器
}

void display_digital_tube(u8 idex,u8 number,bool have_point){
	if(have_point)number&=0x7f;
	LATCH=(LATCH&~LAST_3_BITS_MASK_8)|Digital_tube_idex;//锁存器选择Digital_tube_idex
	DIGITAL_TUBE_IDEX=idex;	//设置显示的数码管
	
	LATCH=(LATCH&~LAST_3_BITS_MASK_8)|Digital_tube;//锁存器选择Digital_tube
	DIGITAL_TUBE=number;//设置显示数值
	
	Delay1ms();//延迟一毫秒
	LATCH=LATCH&~LAST_3_BITS_MASK_8;//关闭锁存器
}

void display_number2(int number_idex,int number){
	display_digital_tube(idex[number_idex],table_sun[number/10],false);
	display_digital_tube(idex[number_idex+1],table_sun[number%10],false);
}